package com.homework.filters;

import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.HashMap;
import java.util.TreeSet;

@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {

    public static HashMap<String, TreeSet<Dimension>> REQUEST_STATISTICS = new HashMap<>();

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        //System.out.println("filter.........................");
        long  startTime  = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long endTime  = System.currentTimeMillis();

        String service = invocation.getServiceName();
        String methodName = invocation.getMethodName();

        String key = service + ":" + methodName;

        synchronized (REQUEST_STATISTICS) {
            TreeSet<Dimension> treeSet = REQUEST_STATISTICS.get(key);
            if(treeSet == null) {
                treeSet = new TreeSet<>();
                REQUEST_STATISTICS.put(key, treeSet);
            }
            treeSet.add(new Dimension(endTime - startTime, startTime));
        }

        return result;
    }


    public static class Dimension implements Comparable<Dimension> {
        public long sendTime;  //请求时间， 毫秒
        public long spendTime; //请求耗时， 毫秒

        public Dimension(long spendTime1, long sendTime1) {
            sendTime  = sendTime1;
            spendTime = spendTime1;
        }

        @Override
        public int compareTo(Dimension o) {
            if(spendTime == o.spendTime) {
                return 0;
            } else if(spendTime < o.spendTime) {
                return -1;
            } else {
                return 1;
            }
        }
    }
}
